/*
 * SystemPanel.java
 *
 * Created on 2008年6月5日, 上午9:08
 */

package gui;
import java.awt.event.MouseEvent;
import javax.swing.GroupLayout;
import model.*;
import abstractmodel.*;
import javax.swing.SwingUtilities;
import java.util.ArrayList;

/**
 *
 * @author  yux
 */
public class SystemPanel extends javax.swing.JPanel {
    private IBook book;
    private IUser ur;
    int type;
    private MainFrame parent;
    MyPopMenu pmenu;
    /** Creates new form SystemPanel */
    public SystemPanel(MainFrame frame, IBook node) {
        book = node;
        type = configure.Global.BOOK_INFO_TYPE;
        parent = frame;
        initComponents();
        if (!setIcon()) 
            System.out.println("设置图标失败！");
    }
    public SystemPanel(MainFrame frame, IUser u) {
        System.out.println("enter SystemPanel ok!");
        type = configure.Global.USER_INFO_TYPE;
        ur = u;
        parent = frame;
        initComponents();
        if (!setIcon()) 
            System.out.println("设置图标失败！");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanelShow = new javax.swing.JPanel();

        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });

        jPanelShow.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jPanelShowMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanelShowLayout = new javax.swing.GroupLayout(jPanelShow);
        jPanelShow.setLayout(jPanelShowLayout);
        jPanelShowLayout.setHorizontalGroup(
            jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 676, Short.MAX_VALUE)
        );
        jPanelShowLayout.setVerticalGroup(
            jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 491, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(jPanelShow);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 694, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private boolean setIcon(){
        int size;
        javax.swing.JLabel[] labels;
        if (type == configure.Global.BOOK_INFO_TYPE) {
            size = book.getAccounts().size();
            labels = new javax.swing.JLabel[size];
            for (int i = 0; i < size; i++) {
                labels[i] = new javax.swing.JLabel(source.SourceImage.fileblackImage);
                labels[i].setText(book.getAccounts().get(i).getAccountInfo().
                        getValue("帐户名称").getString());
            }
        }else if (type == configure.Global.USER_INFO_TYPE){
            size = ur.getBooks().size();
            labels = new javax.swing.JLabel[size];
            for (int i = 0; i < size; i++) {
                labels[i] = new javax.swing.JLabel(source.SourceImage.fileblackImage);
                labels[i].setText(ur.getBooks().get(i).getBookInfo().
                        getValue("账簿名称").getString());
            }     
        } else 
            return false;
        jPanelShow.removeAll();
                /*
        javax.swing.GroupLayout jPanelShowLayout = new javax.swing.GroupLayout(jPanelShow);
        jPanelShow.setLayout(jPanelShowLayout);
        int a = size/4, b = size%4;

        //heng
        javax.swing.GroupLayout.ParallelGroup lineGroup[] = 
                new javax.swing.GroupLayout.ParallelGroup[a+1];
        for (int i = 0; i < a; i++) {
                lineGroup[i] = jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE);
                lineGroup[i].addComponent(labels[i*4]);
                lineGroup[i].addComponent(labels[i*4+1]);
                lineGroup[i].addComponent(labels[i*4+2]);
                lineGroup[i].addComponent(labels[i*4+3]);
        }
        lineGroup[a] = jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE);
        for (int i = 0; i < b; i++) 
            lineGroup[i].addComponent(labels[4*a+i]);
        GroupLayout.SequentialGroup sGroup = jPanelShowLayout.createSequentialGroup();
        sGroup.addGap(42, 42, 42);
        for (int i = 0; i < a+1; i++) {
            sGroup.addGroup(lineGroup[i]);
            if (i == a+1)
                sGroup.addContainerGap(381, Short.MAX_VALUE);
            else
                sGroup.addGap(35, 35, 35);
        }
        jPanelShowLayout.setVerticalGroup(
            jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(sGroup));
        //shu
        
        jPanelShowLayout.setHorizontalGroup(
            jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelShowLayout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addGroup(jPanelShowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanelShowLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(47, 47, 47)
                        .addComponent(jLabel2)))
                .addContainerGap(509, Short.MAX_VALUE))
        );
        */
        jPanelShow.setLayout(new java.awt.GridLayout(5,2));
        for (int i = 0; i < size; i++) 
            jPanelShow.add(labels[i]);
        listen(labels, size); 
        return true;
    }
    
    /**
     * 对Label进行监听
     * @param labels
     * @param size
     */
    private void listen(javax.swing.JLabel[] labels, int size) {
        for (int i = 0; i < size; i++) {
            labels[i].addMouseListener(new java.awt.event.MouseAdapter(){
                @Override//<双击每个label都进入相应账簿或帐户>
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2)
                        labelClickTwice(e);
                    if (e.getClickCount() == 1)
                        labelClickOnce(e);
                }
            });
        }
    }   
    private void labelClickTwice(MouseEvent evt) {
        javax.swing.JLabel label = (javax.swing.JLabel)evt.getSource();
        String name = label.getText();
        if (type == configure.Global.BOOK_INFO_TYPE) {
            int i = 0;
            for (; i < book.getAccounts().size(); i++) 
                if(book.getAccounts().get(i).getAccountInfo().getValue("帐户名称").getString().equals(name)) 
                    break;
            if(i == book.getAccounts().size())
                return;
            
            IAccount account = (IAccount)book.getAccounts().get(i);
            int t = account.getAccountInfo().getType();
            if (t == configure.Global.BANK_ACCOUNT_INFO_TYPE 
                    || t == configure.Global.MONEY_ACCOUNT_INFO_TYPE) {
                class TmpRun implements Runnable {
                    IAccount account;
                    TmpRun(IAccount a) {
                        account=a;
                    }
                    public void run() {
                       //SystemPanel.this.parent.changePanel1(SystemPanel.this, new gui.MoneyAndDebitDetail(account));
                       SystemPanel.this.parent.setjPanelShow(account);
                    }        
                }
                SwingUtilities.invokeLater(new TmpRun(account));
            }else if(t == configure.Global.CREDITCARD_ACCOUNT_INFO_TYPE) {
                class TmpRun implements Runnable {
                    IAccount account;
                    TmpRun(IAccount a) {
                        account=a;
                    }
                    public void run() {
                       //SystemPanel.this.parent.changePanel1(SystemPanel.this, new gui.CreditDetailPanel(account));
                       SystemPanel.this.parent.setjPanelShow(account);
                    }        
                }
                SwingUtilities.invokeLater(new TmpRun(account));
            }
        }else if (type == configure.Global.USER_INFO_TYPE){
            int i = 0;
            System.out.println(name);
            for (; i < ur.getBooks().size(); i++) {
                String get = ur.getBooks().get(i).getBookInfo().getValue("账簿名称").getString();
                if(get.equals(name)) {
                    System.out.println(i);
                    break;
                }
            }
            System.out.println(i);
            if(i == ur.getBooks().size())
                return;
            Book newBook = (Book)ur.getBooks().get(i);
            class TmpRun implements Runnable {
                    Book newBook;
                    TmpRun(Book a) {
                        newBook=a;
                    }
                    public void run() {
                       //SystemPanel.this.parent.changePanel1(SystemPanel.this, new gui.SystemPanel(parent,newBook));
                        SystemPanel.this.parent.setjPanelShow(newBook);
                    }        
                }
                SwingUtilities.invokeLater(new TmpRun(newBook));
        }
    }
    
    private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
        // TODO add your handling code here:
        //System.out.println("mouse released here evt!");
        //jPanelShowMouseReleased(evt);
    }//GEN-LAST:event_formMouseReleased
 
    class MyPopMenu extends javax.swing.JPopupMenu {
        public abstractmodel.IAccount account;
        public abstractmodel.IBook book;
        int menu_type;
        MyPopMenu(abstractmodel.IAccount a) {
            super();
            menu_type = 0;
            account = a;
            book = null;
        }
        MyPopMenu(abstractmodel.IBook a) {
            super();
            menu_type = 1;
            book = a;
            account = null;
        }
        MyPopMenu() {
            super();
            menu_type = 2;
            book = null; account = null;
        }
    }
    
    private void labelClickOnce(MouseEvent evt) {
        if(pmenu != null)
                pmenu.setVisible(false);
        if (evt.getButton() == MouseEvent.BUTTON3) {
            javax.swing.JLabel label = (javax.swing.JLabel)evt.getSource();
            String name = label.getText();
            System.out.println("ClickOnce: "+name);;
            if (type == configure.Global.BOOK_INFO_TYPE) {
                int i = 0;
                for (; i < book.getAccounts().size(); i++)
                    if(name.equals(book.getAccounts().get(i).getAccountInfo().getValue("帐户名称").getString()))
                        break;
                pmenu = new MyPopMenu(book.getAccounts().get(i));
            }else if (type == configure.Global.USER_INFO_TYPE) {
                int i = 0;
                for(; i < ur.getBooks().size(); i++) {
                    String bookName = ur.getBooks().get(i).getBookInfo().getValue("账簿名称").getString();
                    System.out.println(""+i+": "+bookName);
                    if(name.equals(bookName))     break;
                }
                if (i == ur.getBooks().size()) {
                    System.out.println("数据库中没有这个名称的账簿！");
                    return;
                }else
                    pmenu = new MyPopMenu(ur.getBooks().get(i));
            }
            initpmenu(pmenu,evt.getSource());
            pmenu.setLocation(evt.getLocationOnScreen());
            pmenu.setVisible(true);
        }
    }
    
    private void jPanelShowMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelShowMouseReleased
        // TODO add your handling code here:
        if(pmenu != null)
            pmenu.setVisible(false);
        if (evt.getButton() == MouseEvent.BUTTON3) {
            pmenu = new MyPopMenu();
            initpmenu(pmenu, evt.getSource());
            pmenu.setLocation(evt.getLocationOnScreen());
            pmenu.setVisible(true);
        }
    }//GEN-LAST:event_jPanelShowMouseReleased

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked

    }//GEN-LAST:event_formMouseClicked
    
    private void initpmenu(javax.swing.JPopupMenu pmenu, Object o) {
        String[] s = 
        {"查询", "统计", "新建账簿", "新建一个现金帐户", "新建一个借记卡帐户", "新建一个信用卡帐户", "删除"};
        /**
         * 根据鼠标点击对象的不同，可能是打开一个帐户，
         * 也可以是在panel上新建一个账簿或一条明细，popmenu的菜单项也不同
         */
        System.out.println("initpmenu:"+o.getClass().getName());
        if (o.getClass().getName().endsWith("JLabel")) {
            pmenu.add(s[0]);
            pmenu.add(s[1]);
            pmenu.add(s[6]);
            for (int i = 0; i < pmenu.getComponentCount(); i++)
                pmenu.getComponent(i).addMouseListener(new java.awt.event.MouseAdapter(){
                    @Override//单击一个popmenu的监听
                    public void mouseClicked(MouseEvent e) { 
                        javax.swing.JMenuItem menu = (javax.swing.JMenuItem)e.getSource();
                        if (menu.getText().equals("删除"))     delete_listener(e);
                        else    pmenu_Listener_for_label(e);  } });
        }else if (o.getClass().getName().endsWith("JPanel")) {
            if (type == configure.Global.BOOK_INFO_TYPE) {
                pmenu.add(s[0]);
                pmenu.add(s[1]);
                for (int i = 3; i < 6; i++)     pmenu.add(s[i]);
            }else if (type == configure.Global.USER_INFO_TYPE) {
                pmenu.add(s[1]);
                pmenu.add(s[2]);  
            }
            for (int i = 0; i < pmenu.getComponentCount(); i++)
                pmenu.getComponent(i).addMouseListener(new java.awt.event.MouseAdapter(){
                    @Override//单击一个popmenu的监听
                    public void mouseClicked(MouseEvent e) { 
                        System.out.println("init mouse click!");
                        pmenu_Listener_for_panel(e); }
                    });
        }
    }  
    
    private void delete_listener(MouseEvent e) {
        javax.swing.JMenuItem menu = (javax.swing.JMenuItem)e.getSource();
        System.out.println("menuItem click: "+menu.getText());
        if (type == configure.Global.BOOK_INFO_TYPE) 
            book.deleteAccount(pmenu.account);
        else if(type == configure.Global.USER_INFO_TYPE) 
            ur.deleteBook(pmenu.book);
        setIcon();
    }
    
    private void pmenu_Listener_for_panel(MouseEvent evt)  {
        if (pmenu != null)
            pmenu.setVisible(false);
        javax.swing.JMenuItem menu = (javax.swing.JMenuItem)evt.getSource();
        if (type == configure.Global.BOOK_INFO_TYPE) 
            pmenu_Listener_book_panel(menu);
        else if (type == configure.Global.USER_INFO_TYPE)
            pmenu_Listener_user_panel(menu);
    }
    
    /**
     * 对在账簿状态下，除了《删除》菜单外其它popmenu的监听
     * @param menu
     */
    private void pmenu_Listener_book_panel (javax.swing.JMenuItem menu) {
        if (menu.getText().equalsIgnoreCase("查询")){
            String s[] = book.getBookInfo().getTitles();
            String info = "";
            for(int i = 0; i < s.length; i++) 
                info = info+s[i]+": "+book.getBookInfo().getValue(s[i]).getString()+"\n";
            javax.swing.JOptionPane.showMessageDialog(this,info,"查询信息",javax.swing.JOptionPane.INFORMATION_MESSAGE);
        }else if (menu.getText().equalsIgnoreCase("统计")){
            String title[] = {"帐户名称", "余额"};
            int size = book.getAccounts().size();
            String value[][];
            value = new String[size][2];
            for(int i = 0; i < size; i++) {
                value[i][0] = book.getAccounts().get(i).getAccountInfo().getValue("帐户名称").toString();
                value[i][1] = book.getAccounts().get(i).getTotalLeftMoney()+"";
            }
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "账簿中所有帐户余额的分布", true);
            dialog.add(new gui.AccountStatistic(value, title));
            dialog.setVisible(true);
        }else if (menu.getText().equalsIgnoreCase("新建一个现金帐户")){
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "新建现金帐户", true);
            dialog.add(new gui.AddMoneyAccountPanel(book));
            dialog.setSize(500,550);
            dialog.setVisible(true);
            javax.swing.JLabel newLabel = new javax.swing.JLabel(source.SourceImage.fileblackImage);
            newLabel.setText(book.getAccounts().get(book.getAccounts().size()-1).toString());
            jPanelShow.add(newLabel);
        }else if (menu.getText().equalsIgnoreCase("新建一个借记卡帐户")){
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "新建一个借记卡帐户", true);
            dialog.add(new gui.AddDebitAccountPanel(book));
            dialog.setSize(500,550);
            dialog.setVisible(true);
            javax.swing.JLabel newLabel = new javax.swing.JLabel(source.SourceImage.fileblackImage);
            newLabel.setText(book.getAccounts().get(book.getAccounts().size()-1).toString());
            jPanelShow.add(newLabel);
        }else if (menu.getText().equalsIgnoreCase("新建一个信用卡帐户")){
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent,"新建一个信用卡帐户",true);
            dialog.add(new gui.AddCreditAccountPanel(book));
            dialog.setSize(500,550);
            dialog.setVisible(true);
            javax.swing.JLabel newLabel = new javax.swing.JLabel(source.SourceImage.fileblackImage);
            newLabel.setText(book.getAccounts().get(book.getAccounts().size()-1).toString());
            jPanelShow.add(newLabel);
        }
    }
    private void pmenu_Listener_user_panel(javax.swing.JMenuItem menu) {
        if (menu.getText().equalsIgnoreCase("统计")){
            ArrayList<String> names = ur.getStatistics(StatisticsType.PIE).getNames();
            ArrayList<Double> values = ur.getStatistics(StatisticsType.PIE).getValues();
            System.out.println(names +"\n"+values);
            String valueM[][];
            int size = names.size();
            valueM = new String[size][2];
            for(int i = 0; i < size; i++) {
                valueM[i][0] = names.get(i);
                valueM[i][1] = values.get(i)+"";
            }
            String[] title = {"账簿名称", "余额"};
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "我的账本中所有帐户余额的分布", true);
            dialog.add(new gui.AccountStatistic(valueM, title));
            dialog.setVisible(true);
        }else if (menu.getText().equalsIgnoreCase("新建账簿")){
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent,"新建账簿",true);
            dialog.add(new gui.AddBookPanel(ur));
            dialog.setSize(500,550);
            dialog.setVisible(true);
            javax.swing.JLabel newLabel = new javax.swing.JLabel(source.SourceImage.fileblackImage);
            newLabel.setText(ur.getBooks().get(ur.getBooks().size()-1).toString());
            jPanelShow.add(newLabel);
        }
    }
    
    private void pmenu_Listener_for_label (MouseEvent evt) {
        if (pmenu != null)
            pmenu.setVisible(false);
        javax.swing.JMenuItem menu = (javax.swing.JMenuItem)evt.getSource();
        System.out.println(menu.getText());
        if (type == configure.Global.BOOK_INFO_TYPE) 
            pmenu_Listener_book_label(menu);
        else if (type == configure.Global.USER_INFO_TYPE)
            pemu_listener_user_label(menu);
    }
    
    private void pmenu_Listener_book_label(javax.swing.JMenuItem menu){
        if (menu.getText().equalsIgnoreCase("查询")){
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "查询", true);
            gui.searchInABook p = new gui.searchInABook(book);
            dialog.add(p);
            dialog.setSize(400,300);
            dialog.setLocationRelativeTo(this);
            dialog.setVisible(true);
            String v = p.returnValue();
            try{
                ArrayList<IAccount> accounts = 
                        book.getAccountsLeftMoneyMoreThan(Double.valueOf(v).doubleValue());
                int size = accounts.size();
            }catch(Exception e) {
                
            }
        }else if(menu.getText().equalsIgnoreCase("统计")){
            
        }
    }
    
    private void pemu_listener_user_label(javax.swing.JMenuItem menu) {
        if (menu.getText().equalsIgnoreCase("查询")){
            String s[] = pmenu.book.getBookInfo().getTitles();
            String info = "";
            for(int i = 0; i < s.length; i++) 
                info = info+s[i]+": "+pmenu.book.getBookInfo().getValue(s[i]).getString()+"\n";
            javax.swing.JOptionPane.showMessageDialog(this,info,"查询信息",javax.swing.JOptionPane.INFORMATION_MESSAGE);
        }else if (menu.getText().equalsIgnoreCase("统计")){
            String title[] = {"帐户名称", "余额"};
            int size = pmenu.book.getAccounts().size();
            String value[][];
            value = new String[size][2];
            for(int i = 0; i < size; i++) {
                value[i][0] = pmenu.book.getAccounts().get(i).getAccountInfo().getValue("帐户名称").toString();
                value[i][1] = pmenu.book.getAccounts().get(i).getTotalLeftMoney()+"";
            }
            javax.swing.JDialog dialog = new javax.swing.JDialog(parent, "账簿中所有帐户余额的分布", true);
            dialog.add(new gui.AccountStatistic(value, title));
            dialog.setVisible(true);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanelShow;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    
}
